using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartLink.Infrastructure
{
    /// <summary>
    /// 计算日期 ,格式化日期
    /// </summary>
    public static class TimeHelper
    {
        /// <summary>
        /// 计算两个日期的时间间隔
        /// </summary>
        /// <param name="DateTime1">第一个日期和时间</param>
        /// <param name="DateTime2">第二个日期和时间</param>
        /// <returns>年月日字符串</returns>
        public static string DateDiffSrting(DateTime DateTime1, DateTime DateTime2)
        {
            return DateDiff(DateTime1, DateTime2).ToString("zh");
        }

        /// <summary>
        /// 如果2大于1返回true,如果2小于1返回false
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static bool Compare(DateTime DateTime1, DateTime DateTime2)
        {
            int i = DateTime.Compare(DateTime1, DateTime2);
            if (i > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 如果2大于1返回true,如果2小于1返回false
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static bool Compare(string DateTime1, string DateTime2)
        {
            return Compare(Convert.ToDateTime(DateTime1), Convert.ToDateTime(DateTime2));
        }

        /// <summary>
        ///  返回时间间隔的绝对值,单位秒
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static double DateDiffValue(DateTime DateTime1, DateTime DateTime2)
        {
            TimeSpan ts = DateDiff(DateTime1, DateTime2);
            return ts.TotalSeconds;
        }


        /// <summary>
        /// 计算两个日期的时间间隔的绝对值
        /// </summary>
        /// <param name="DateTime1">第一个日期和时间</param>
        /// <param name="DateTime2">第二个日期和时间</param>
        /// <returns></returns>
        public static TimeSpan DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            //string dateDiff = null;

            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            return ts;
        }

        public static string DateDiffString(DateTime DateTime1, DateTime DateTime2)
        {
            return DateDiff(DateTime1, DateTime2).ToMyString();
        }

        public static string ToMyString(this TimeSpan s, string fatmart = "zh")
        {
            string dateDiff = null;
            switch (fatmart)
            {
                case "zh":
                    dateDiff = s.Days > 0 ? s.Days.ToString() + "天" : "";
                    dateDiff += s.Hours > 0 ? s.Hours.ToString() + "小时" : "";
                    dateDiff += s.Minutes > 0 ? s.Minutes.ToString() + "分钟" : "";
                    dateDiff += s.Seconds > 0 ? s.Seconds.ToString() + "秒" : "";

                    break;
            }

            return dateDiff;
        }

        ///<summary>
        ///由秒数得到日期几天几小时
        ///</summary>
        ///<param name="t">秒数</param>
        ///<param name="type">0：转换后带秒，1：转换后不带秒</param>
        ///<returns>几天几小时几分几秒</returns>
        public static string parseTimeSeconds(string t, int type)
        {
            if (t.IsNumber())
            {
                int i = Convert.ToInt32(Math.Floor(Convert.ToDouble(t)));
                return parseTimeSeconds(i, type);
            }
            else
            {
                return "";
            }
        }


        ///<summary>
        ///由秒数得到日期几天几小时
        ///</summary>
        ///<param name="t">秒数</param>
        ///<param name="type">0：转换后带秒，1：转换后不带秒</param>
        ///<returns>几天几小时几分几秒</returns>
        public static string parseTimeSeconds(int t, int type)
        {
            if (t < 0)
            {
                return "";
            }
            string r = "";
            int day, hour, minute, second;

            if (t >= 86400)  //天,
            {
                day = Convert.ToInt32(t / 86400);
                hour = Convert.ToInt32((t % 86400) / 3600);
                minute = Convert.ToInt32((t % 86400 % 3600) / 60);
                second = Convert.ToInt32(t % 86400 % 3600 % 60);
                if (type == 0)
                    r = day + ("天") + hour + ("小时") + minute + ("分钟") + second + ("秒");
                else
                    r = day + ("天") + hour + ("小时") + minute + ("分钟");

            }
            else if (t >= 3600)//时,
            {
                hour = Convert.ToInt32(t / 3600);
                minute = Convert.ToInt32((t % 3600) / 60);
                second = Convert.ToInt32(t % 3600 % 60);
                if (type == 0)
                    r = hour + ("小时") + minute + ("分钟") + second + ("秒");
                else
                    r = hour + ("小时") + minute + ("分钟");
            }
            else if (t >= 60)//分
            {
                minute = Convert.ToInt32(t / 60);
                second = Convert.ToInt32(t % 60);
                if (type == 0)
                {
                    r = minute + ("分钟") + second + ("秒");
                }
                else
                {
                    r = minute + ("分钟");
                }

            }
            else
            {
                second = Convert.ToInt32(t);
                if (type == 0)
                {
                    r = second + ("秒");
                }
                else
                {
                    r = ("0分钟");
                }

            }
            return r;
        }

        /// <summary>
        /// 当前日期时间，转换为秒
        /// </summary>
        /// <returns>秒数</returns>
        public static string xDateSeconds()
        {
            long xdateseconds = 0;
            DateTime xdatenow = DateTime.UtcNow;     //当前UTC时间


            long xminute = 60;      //一分种60秒
            long xhour = 3600;
            long xday = 86400;
            long byear = 1970;//从1970-1-1 0：00：00开始到现在所过的秒
            long[] xmonth = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
            long[] xyear = { 365, 366 };
            long num = 0;

            xdateseconds += xdatenow.Second;    //算秒
            xdateseconds += xdatenow.Minute * xminute;      //算分
            xdateseconds += xdatenow.Hour * xhour;      //算时
            xdateseconds += (xdatenow.Day - 1) * xday;        //算天

            //算月(月换成天算)
            if (DateTime.IsLeapYear(xdatenow.Year))
            {
                xdateseconds += (xmonth[xdatenow.Month - 1] + 1) * xday;
            }
            else
            {
                xdateseconds += (xmonth[xdatenow.Month - 1]) * xday;
            }

            //算年（年换成天算）
            long lyear = xdatenow.Year - byear;

            for (int i = 0; i < lyear; i++)
            {
                if (DateTime.IsLeapYear((int)byear + i))
                {
                    num++;
                }
            }

            xdateseconds += ((lyear - num) * xyear[0] + num * xyear[1]) * xday;

            return xdateseconds.ToString();
        }

        /// <summary>
        /// 秒数转日期
        /// </summary>
        /// <param name="Value">秒数</param>
        /// <returns>日期</returns>
        public static DateTime GetGMTDateTime(int Value)
        {
            //秒数转时间日期
            //GMT时间从2000年1月1日开始，先把它作为赋为初值
            long Year = 2000, Month = 1, Day = 1;
            long Hour = 0, Min = 0, Sec = 0;
            //临时变量
            long iYear = 0, iDay = 0;
            long iHour = 0, iMin = 0, iSec = 0;
            //计算文件创建的年份
            iYear = Value / (365 * 24 * 60 * 60);
            Year = Year + iYear;
            //计算文件除创建整年份以外还有多少天
            iDay = (Value % (365 * 24 * 60 * 60)) / (24 * 60 * 60);
            //把闰年的年份数计算出来
            int RInt = 0;
            for (int i = 2000; i < Year; i++)
            {
                if ((i % 4) == 0)
                    RInt = RInt + 1;
            }
            //计算文件创建的时间(几时)
            iHour = ((Value % (365 * 24 * 60 * 60)) % (24 * 60 * 60)) / (60 * 60);
            Hour = Hour + iHour;
            //计算文件创建的时间(几分)
            iMin = (((Value % (365 * 24 * 60 * 60)) % (24 * 60 * 60)) % (60 * 60)) / 60;
            Min = Min + iMin;
            //计算文件创建的时间(几秒)
            iSec = (((Value % (365 * 24 * 60 * 60)) % (24 * 60 * 60)) % (60 * 60)) % 60;
            Sec = Sec + iSec;
            DateTime t = new DateTime((int)Year, (int)Month, (int)Day, (int)Hour, (int)Min, (int)Sec);
            DateTime t1 = t.AddDays(iDay - RInt);
            return t1;
        }

        public static string GetUnixTime(DateTime curTime)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(curTime.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }

        /// <summary>
        /// 将时间戳（秒 为单位）转换为DateTime
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime GetDateTimeByUnixTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }
        /// <summary>
        /// 将Unix时间戳转换为DateTime类型时间
        /// </summary>
        /// <param name="d">double 型数字</param>
        /// <returns>DateTime</returns>
        public static System.DateTime ConvertIntDateTime(double d)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddMilliseconds(d);
            return time;
        }

        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>long</returns>
        public static long ConvertDateTimeInt(System.DateTime time)
        {
            //double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            //intResult = (time- startTime).TotalMilliseconds;
            long t = (time.Ticks - startTime.Ticks) / 10000;            //除10000调整为13位
            return t;
        }

        /// <summary>
        /// 取得两个时间的较大值
        /// </summary>
        /// <param name="dateTime1">时间 1</param>
        /// <param name="dateTime2">时间 2</param>
        /// <returns>两个时间的较大值</returns>
        public static DateTime GreaterTime(DateTime dateTime1, DateTime dateTime2)
        {
            return dateTime1 > dateTime2 ? dateTime1 : dateTime2;
        }
        /// <summary>
        /// 取得两个时间的较小值
        /// </summary>
        /// <param name="dateTime1">时间 1</param>
        /// <param name="dateTime2">时间 2</param>
        /// <returns>两个时间的较小值</returns>
        public static DateTime LessTime(DateTime dateTime1, DateTime dateTime2)
        {
            return dateTime1 < dateTime2 ? dateTime1 : dateTime2;
        }

        /// <summary>  
        /// 取得某月的第一天  
        /// </summary>  
        /// <param name="datetime">要取得月份第一天的时间</param>  
        /// <returns></returns>  
        public static DateTime FirstDayOfMonth(this DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>  
        /// 取得某月的最后一天  
        /// </summary>  
        /// <param name="datetime">要取得月份最后一天的时间</param>  
        /// <returns></returns>  
        public static DateTime LastDayOfMonth(this DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }
    }
}
